package cn.fanyamin.web.struts;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.struts.ContextLoaderPlugIn;

import cn.fanyamin.business.DWRService;
import cn.fanyamin.domain.UserCategory;
import cn.fanyamin.domain.Module;
import cn.fanyamin.domain.RepeatInfo;
import cn.fanyamin.domain.User;


public class AjaxAction {
    
    public int isUserExisted(User user, HttpSession session){
         return getDWRService(session).isUserExisted(user);
    }
    
    public List<Module> getModuleList(int roleID, HttpSession session){
        if(!isUserLogin(session)) {
            return new ArrayList<Module>();
        }
        
        return getDWRService(session).getModuleList(roleID);
    }
    
    public List<UserCategory> getCategoryList(int categoryType, int userID, HttpSession session){
        if(!isUserLogin(session)) {
            return new ArrayList<UserCategory>();
        }
        
        return getDWRService(session).getCategoryList(categoryType, userID);
    }
    
    public List<Module> getFavoriteModules(int userID, HttpSession session){
        User aUser = (User)session.getAttribute("sess_user");
        if(aUser == null) {
            return new ArrayList<Module>();
        }
        Module aModule = (Module)session.getAttribute("sess_module");
        
        return getDWRService(session).getFavoriteModules(aUser,aModule);
    }
    
    public RepeatInfo getRepeatInfo(int repeatID, HttpSession session) {
        if(!isUserLogin(session)) {
            return new RepeatInfo();
        }
        return getDWRService(session).getRepeatInfo(repeatID);
    }
    
    protected boolean isUserLogin(HttpSession session) {
        return null != (User)session.getAttribute("sess_user");
    }
    
    private DWRService getDWRService(HttpSession session) {
        WebApplicationContext wac=(WebApplicationContext)session.getServletContext()
        .getAttribute(ContextLoaderPlugIn.SERVLET_CONTEXT_PREFIX); 
        DWRService dwrService = (DWRService) wac.getBean("dwrService");
        return dwrService;
    }
}
